<template>
  <ych-modal
    :fullscreen="true"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :destroyOnClose="true"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :closable="false"
    :footer="null">
    <a-spin :spinning="confirmLoading">
      <div class="model-designer-toolbar">
        <span class="model-designer-title">{{ title }}</span>
        <div class="model-designer-button-group">
          <a-popconfirm placement="bottomRight" :title="$t('m.common.tip.save_confirm')" @confirm="() => handleOk()">
            <a-button icon="save" type="primary">{{ $t('m.common.button.save') }}</a-button>
          </a-popconfirm>
          <a-button icon="chrome" @click="handleOpenPreviewModal">{{$t('m.common.button.preview')}}</a-button>
          <a-button icon="credit-card" @click="handleOpenJsonModal">{{$t('m.eform.formDesign.label.generateJSON')}}</a-button>
          <a-button icon="delete" @click="handleReset">{{ $t('m.common.button.clear') }}</a-button>
          <a-button type="link" icon="close" @click="handleCancel"></a-button>
        </div>
      </div>

      <a-form :form="form">
        <a-row>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appview.entity.viewName')" :labelCol="labelCol" :wrapperCol="wrapperCol"
                         style="margin-top: 12px;">
              <a-input v-decorator="[ 'viewName', validatorRules.viewName]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appview.entity.viewCode')" :labelCol="labelCol" :wrapperCol="wrapperCol"
                         style="margin-top: 12px;">
              <a-input v-decorator="[ 'viewCode', validatorRules.viewCode]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('m.eform.appform.entity.objectName')" :labelCol="labelCol" :wrapperCol="wrapperCol"
                         style="margin-top: 12px;">
              <object-code-tag v-decorator="[ 'objectCode', validatorRules.objectCode]" :placeholder="$t('m.eform.formDesign.label.qing-xuan-ze-er-mo-xing')"
                               :radio="false"
                               :groupId="groupId">
                <a-tooltip slot="addonAfter">
                  <template slot="title">
                    {{ $t('m.eform.formDesign.label.yong-yu-she-zhi-lie-biao-jian-de-lian-dong-guan-xi') }} </template>
                  <ych-icon type="question"/>
                </a-tooltip>
              </object-code-tag>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol2" :wrapperCol="wrapperCol2" style="margin-top: 12px;">
              <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]"></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <layout-container ref="layoutContainer" :height="height" :data="layoutModel"
                              :groupId="groupId"></layout-container>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>

    <k-json-modal ref="jsonModal"/>
    <layout-preview ref="layoutPreview" type="dragLayout"></layout-preview>
  </ych-modal>
</template>

<script>

import {httpAction, getAction} from '@/api/manage'
import ObjectCodeTag from '../select/tag/ObjectCodeTag'
import YchConstant from "@/api/YchConstant";
import LayoutContainer from '../layoutMaking/LayoutContainer'
import kJsonModal from "./designer/packages/KFormDesign/module/jsonModal";
import LayoutPreview from '../layoutMaking/LayoutPreview'

const defaultLayoutModel = {
  list: [],
  config: {
    percent: false
  }
}
export default {
  name: 'ActAppViewDragLayoutModal',
  components: {
    ObjectCodeTag,
    LayoutContainer,
    kJsonModal,
    LayoutPreview,
  },
  props: {
    groupId: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
      title: this.$t('m.common.label.operate'),
      visible: false,
      bodyStyle: {
        padding: 0,
        margin: 0
      },
      model: {},
      layoutModel: JSON.parse(JSON.stringify(defaultLayoutModel)),
      height: document.body.clientHeight - 52 - 66 - 12 + 'px',
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      labelCol2: {
        xs: {span: 24},
        sm: {span: 12}
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 12}
      },
      confirmLoading: false,
      validatorRules: {
        viewName: {rules: [{required: true, message: this.$t('m.eform.appview.verify.viewName')},]},
        viewCode: {
          rules: [{required: true, message: this.$t('m.eform.appview.verify.viewCode')},
            {validator: this.checkCode}]
        },
        objectCode: {},
        orderNum: {
          initialValue: 1 // TODO 默认值取数据库最大值+10
        },
      },
      url: {
        add: YchConstant.PREFIX_EFORM + '/manage/actAppView/add',
        edit: YchConstant.PREFIX_EFORM + '/manage/actAppView/edit',
        checkCode: YchConstant.PREFIX_EFORM + '/manage/actAppView/checkCode',
      },
    }
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.layoutModel = this.model.viewLayoutl ? JSON.parse(this.model.viewLayoutl) : JSON.parse(JSON.stringify(defaultLayoutModel))
      this.historyData();
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(this.lodash.pick(this.model, 'viewName', 'viewCode', 'objectCode', 'orderNum'))
      })
    },
    copy(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.model.id = undefined
      this.layoutModel = this.model.viewLayoutl ? JSON.parse(this.model.viewLayoutl) : JSON.parse(JSON.stringify(defaultLayoutModel))
      this.historyData();
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(this.lodash.pick(this.model, 'viewName', 'viewCode', 'objectCode', 'orderNum'))
      })
    },
    historyData() {
      // TODO 处理历史数据，把新的属性自动加上
    },
    handleOk() {
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          formData.groupId = this.groupId
          formData.viewLayoutl = JSON.stringify(this.layoutModel)
          formData.viewType = 'dragLayout'
          this.confirmLoading = true
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              this.messageUtil.success(res.message)
              this.$emit('ok')
              this.close()
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    checkCode(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(value)) {
        callback(this.$t('m.common.tip.code_format'))
        return
      }
      getAction(this.url.checkCode, {
        value: value,
        id: this.model.id
      }).then((res) => {
        res.success ? callback() : callback(res.message)
      })
    },
    handleReset() {
      this.$refs.layoutContainer.selectModel({})
      this.layoutModel = JSON.parse(JSON.stringify(defaultLayoutModel))
    },
    handleOpenPreviewModal() {
      this.$refs.layoutPreview.objectCode = this.form.getFieldValue('objectCode')
      this.$refs.layoutPreview.jsonData = {dragLayout: this.layoutModel}
      this.$refs.layoutPreview.show();
    },
    handleOpenJsonModal() {
      this.$refs.jsonModal.jsonData = this.layoutModel
      this.$refs.jsonModal.visible = true
    }
  }
}
</script>
<style scoped lang="less">
.model-designer-toolbar {
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding: 0px 10px 0px 10px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;

  .model-designer-title {
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    font-weight: 600;
    margin: 0px 0px 0px 10px;
    display: inline-block;
  }

  .model-designer-button-group {
    display: inline-block;
    float: right;

    .ant-btn {
      margin: 6px 6px;
    }
  }
}
</style>
